<!-- eslint-disable vue/max-attributes-per-line -->
<!-- eslint-disable vue/html-closing-bracket-newline -->
<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <!-- 公司设置 -->
        <el-tabs>
          <el-tab-pane label="用户管理" name="first">用户管理</el-tab-pane>

          <!-- 新增角色按钮 -->
          <el-row style="height: 60px">
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="hAdd"
              >新增角色</el-button
            >
          </el-row>

          <el-table :data="roles" style="width: 100%">
            <el-table-column label="序号" type="index" :index="hIndex" />
            <el-table-column label="角色名称" prop="name" />
            <el-table-column label="描述" prop="description" />
            <el-table-column align="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="success"
                  @click="hAssign(scope.row.id)"
                  >分配权限</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button
                >
                <el-button size="mini" type="danger" @click="hDel(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tabs>

        <!-- :current-page="currentPage" 设置当前页码
          :page-sizes="[100, 200, 300, 400]" 选择每页提供的条数
          :page-size="100" 当前每页提供的条数
          layout="total, sizes, prev, pager, next, jumper"
          :total="400"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[2, 5, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible.sync="showDialogAssign">
        <assign-permission
          v-if="showDialogAssign"
          :role-id="roleId"
          :show-dialog-assign.sync="showDialogAssign"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignPermission from './assignPermission'
import { getRoles, delRoles, addRoles, updateRoles } from '@/api/settings'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roleId: '',
      showDialogAssign: false, // 分配权限对话框
      isEdit: false,
      roles: [],
      currentPage: 1,
      pageSize: 2,
      total: 0,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  created() {
    this.loadRoles()
  },
  methods: {
    // 让每页的序号不是从1开始，而是延续上一页的序号
    hIndex(index) {
      // console.log(index)
      // 当前序号 + ( 当前页数 - 1 ) * 每页条数 + 1
      return index + (this.currentPage - 1) * this.pageSize + 1
    },
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.currentPage, this.pageSize)
        console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 更新每页显示的条数
      this.currentPage = 1
      this.pageSize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.loadRoles()
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index, row)
      // 2. 显示弹层
      this.showDialog = true
      // 1. 把当前的数据直接给表单
      this.roleForm = row
      // console.log(row)
      this.isEdit = true
      this.roleForm = { ...row }
    },
    async doEdit() {
      await updateRoles(this.roleForm)
      this.$message.success('编辑成功')
      // 2. 关闭弹层
      this.showDialog = false
      this.loadRoles()
    },
    // handleDelete(index, row) {
    //   console.log(index, row)
    // },
    // 删除功能
    hDel(id) {
      alert(1)
      this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 做删除
          this.doDel(id)
        })
        .catch(() => {})
    },
    async doDel(id) {
      try {
        const res = await delRoles(id)
        console.log(res)
        // 1. 提示
        this.$message({ type: 'success', message: '删除成功!' })
        if (this.roles.length === 1) {
          this.currentPage--
          if (this.currentPage <= 0) {
            this.currentPage = 1
          }
        }
        // 2. 更新数据
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: '删除失败' })
      }
    },
    // 用户点击了确认
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // 做具体的添加动作
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    async doAdd() {
      await addRoles(this.roleForm)
      this.$message.success('添加成功')
      // 2. 关闭弹层
      this.showDialog = false
      this.total++ // 总数++
      this.currentPage = Math.ceil(this.total / this.pageSize)
      // 3.重发请求
      this.loadRoles()
    },
    hClose() {
      // 充值表单数据，清空表单校验结果
      this.$refs.roleForm.resetFields()
      this.roleForm.id = ''
      this.roleForm.name = ''
      this.roleForm.description = ''
    },
    hAssign(id) {
      this.showDialogAssign = true
      this.roleId = id
    }
  }
}
</script>
